$(document).ready(function() {
    let transactions = [];
    let totalPages = 1;
    let currentPage = 1;
    let itemsPerPage = 10;
    let fundList = []; // 用于存储基金列表

    // 自定义alert函数
    function customAlert(message) {
        $('#customAlertMessage').text(message);
        $('#customAlertModal').modal('show');
    }

    // 获取基金列表用于搜索建议
    function fetchFundsForSearch(fundCode, callback) {
        if (!fundCode) return;
        
        $.ajax({
            url: `/api/funds/getFundsByConditions`,
            type: 'GET',
            data: {
                fundCode: fundCode || '',
                pageSize: 10
            },
            success: function(data) {
                if (data && data.records) {
                    fundList = data.records;
                    if (callback) callback(fundList);
                }
            },
            error: function(xhr, status, error) {
                console.error('Error fetching funds:', error);
            }
        });
    }

    function fetchTransactions() {
        const fundCode = $('#searchFundCode').val();
        const transactionType = $('#searchTransactionType').val();
        itemsPerPage = parseInt($('#itemsPerPage').val(), 10);
        const queryParams = {
            fundCode: fundCode || '',
            transactionType: transactionType || '',
            pageNo: currentPage,
            pageSize: itemsPerPage
        };

        $.ajax({
            url: `/api/transactions/getTransactionsByConditions`,
            type: 'GET',
            data: queryParams,
            success: function(data) {
                if (!data || !data.records) {
                    console.error('Invalid data received:', data);
                    customAlert('获取数据失败，请检查输入条件或稍后重试。');
                    return;
                }

                transactions = data.records;
                totalPages = data.pages;
                renderTransactionTable(transactions);
                updatePagination();
            },
            error: function(xhr, status, error) {
                console.error('Error fetching transactions:', error);
                customAlert('获取数据失败，请检查网络连接或稍后重试。');
            }
        });
    }

    function renderTransactionTable(data) {
        const transactionTableBody = $('#transactionTableBody');
        transactionTableBody.empty();

        if (data.length > 0) {
            data.forEach(transaction => {
                const tr = $('<tr>');
                tr.append($('<td>').text(transaction.fundCode));
                tr.append($('<td>').text(transaction.fundName));
                tr.append($('<td>').text(transaction.transactionTypeName));
                tr.append($('<td>').text(transaction.shares));
                tr.append($('<td>').text(transaction.price));
                tr.append($('<td>').text(transaction.fee || '0.00'));
                tr.append($('<td>').text(transaction.amount || '0.00'));
                tr.append($('<td>').text(transaction.transactionTime || ''));
                
                const actionsTd = $('<td>');
                actionsTd.html(`
                    <button class="btn btn-sm btn-warning me-2" onclick="editTransaction(${transaction.id})">编辑</button>
                    <button class="btn btn-sm btn-danger" onclick="deleteTransaction(${transaction.id})">删除</button>
                `);
                tr.append(actionsTd);
                transactionTableBody.append(tr);
            });
        } else {
            transactionTableBody.html('<tr><td colspan="9" class="text-center">暂无数据</td></tr>');
        }
    }

    // 更新分页控件
    function updatePagination() {
        // 更新页码显示
        $('#currentPage').text(currentPage);
        $('#totalPages').text(totalPages);
        
        // 更新上一页和下一页按钮状态
        if (currentPage <= 1) {
            $('#prevPage').addClass('disabled');
        } else {
            $('#prevPage').removeClass('disabled');
        }
        
        if (currentPage >= totalPages) {
            $('#nextPage').addClass('disabled');
        } else {
            $('#nextPage').removeClass('disabled');
        }
    }

    function handleSizeChange(newSize) {
        itemsPerPage = newSize;
        currentPage = 1; // 重置到第一页
        fetchTransactions();
    }

    function handleCurrentChange(newPage) {
        // 确保页码在有效范围内
        if (newPage < 1) newPage = 1;
        if (newPage > totalPages) newPage = totalPages;
        
        if (newPage !== currentPage) {
            currentPage = newPage;
            fetchTransactions();
        }
    }

    function addNewTransaction() {
        const fundCode = $('#addFundCode').val();
        const fundName = $('#addFundName').val();
        const transactionType = $('#addTransactionType').val();
        const shares = $('#addShares').val();
        const price = $('#addPrice').val();
        const fee = $('#addFee').val();
        const transactionTime = $('#addTransactionTime').val();

        if (fundCode.trim() === '') {
            customAlert('基金代码不能为空');
            return;
        }

        if (fundName.trim() === '') {
            customAlert('基金名称不能为空');
            return;
        }

        if (transactionType === '') {
            customAlert('交易类型不能为空');
            return;
        }

        if (shares.trim() === '' || parseFloat(shares) <= 0) {
            customAlert('份额必须大于0');
            return;
        }

        if (price.trim() === '' || parseFloat(price) <= 0) {
            customAlert('价格必须大于0');
            return;
        }

        if (transactionTime.trim() === '') {
            customAlert('交易时间不能为空');
            return;
        }

        const newTransaction = {
            fundCode: fundCode,
            fundName: fundName,
            transactionType: transactionType,
            shares: shares,
            price: price,
            fee: fee,
            transactionTime: transactionTime
        };

        $.ajax({
            url: `/api/transactions/addTransaction`,
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(newTransaction),
            success: function(data) {
                $('#addTransactionForm')[0].reset();
                $('#addTransactionModal').modal('hide');
                $('#fundSuggestions').hide();
                fetchTransactions();
                customAlert('新增成功');
            },
            error: function(xhr, status, error) {
                console.error('Error adding transaction:', error);
                customAlert('新增交易记录失败');
            }
        });
    }

    function saveEditTransaction() {
        const transactionId = $('#editTransactionId').val();
        const fundCode = $('#editFundCode').val();
        const fundName = $('#editFundName').val();
        const transactionType = $('#editTransactionType').val();
        const shares = $('#editShares').val();
        const price = $('#editPrice').val();
        const fee = $('#editFee').val();
        const transactionTime = $('#editTransactionTime').val();

        if (fundName.trim() === '') {
            customAlert('基金名称不能为空');
            return;
        }

        if (transactionType === '') {
            customAlert('交易类型不能为空');
            return;
        }

        if (shares.trim() === '' || parseFloat(shares) <= 0) {
            customAlert('份额必须大于0');
            return;
        }

        if (price.trim() === '' || parseFloat(price) <= 0) {
            customAlert('价格必须大于0');
            return;
        }

        if (transactionTime.trim() === '') {
            customAlert('交易时间不能为空');
            return;
        }

        const updatedTransaction = {
            id: transactionId,
            fundCode: fundCode,
            fundName: fundName,
            transactionType: transactionType,
            shares: shares,
            price: price,
            fee: fee,
            transactionTime: transactionTime
        };

        $.ajax({
            url: `/api/transactions/updateTransaction`,
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(updatedTransaction),
            success: function(data) {
                $('#editTransactionModal').modal('hide');
                fetchTransactions();
                customAlert('信息更新成功');
            },
            error: function(xhr, status, error) {
                console.error('Error updating transaction:', error);
                customAlert('更新交易记录失败');
            }
        });
    }

    function deleteTransaction(id) {
        if (confirm('确定要删除该交易记录吗？')) {
            $.ajax({
                url: `/api/transactions/deleteTransaction/${id}`,
                type: 'POST',
                success: function() {
                    fetchTransactions();
                    customAlert('删除成功');
                },
                error: function(xhr, status, error) {
                    console.error('Error deleting transaction:', error);
                    customAlert('删除交易记录失败');
                }
            });
        }
    }

    // 显示基金建议列表
    function showFundSuggestions(funds) {
        const suggestionsContainer = $('#fundSuggestions');
        suggestionsContainer.empty();
        
        if (funds.length > 0) {
            funds.forEach(fund => {
                const item = $(`<a href="#" class="list-group-item list-group-item-action">
                    <div class="d-flex w-100 justify-content-between">
                        <h6 class="mb-1">${fund.fundCode}</h6>
                        <small>${fund.fundName}</small>
                    </div>
                </a>`);
                
                item.on('click', function(e) {
                    e.preventDefault();
                    $('#addFundCode').val(fund.fundCode);
                    $('#addFundName').val(fund.fundName);
                    suggestionsContainer.hide();
                });
                
                suggestionsContainer.append(item);
            });
            suggestionsContainer.show();
        } else {
            suggestionsContainer.hide();
        }
    }

    // 全局函数供HTML调用
    window.editTransaction = function(id) {
        const transaction = transactions.find(p => p.id == id);
        if (transaction) {
            $('#editTransactionId').val(transaction.id);
            $('#editFundCode').val(transaction.fundCode);
            $('#editFundName').val(transaction.fundName);
            $('#editTransactionType').val(transaction.transactionType);
            $('#editShares').val(transaction.shares);
            $('#editPrice').val(transaction.price);
            $('#editFee').val(transaction.fee || '0');
            $('#editTransactionTime').val(transaction.transactionTime);
            $('#editTransactionModal').modal('show');
        }
    };

    window.deleteTransaction = deleteTransaction;

    // 事件绑定
    $('#fetchTransactionsButton').on('click', fetchTransactions);
    $('#saveAddTransaction').on('click', addNewTransaction);
    $('#saveEditTransaction').on('click', saveEditTransaction);

    $('#itemsPerPage').on('change', function() {
        handleSizeChange(parseInt($(this).val(), 10));
    });

    $('#pPage').on('click', function(e) { 
        e.preventDefault();
        if (currentPage > 1) {
            handleCurrentChange(currentPage - 1); 
        }
    });
    
    $('#nPage').on('click', function(e) { 
        e.preventDefault();
        if (currentPage < totalPages) {
            handleCurrentChange(currentPage + 1); 
        }
    });

    // 基金代码输入框键盘输入时，提供搜索建议
    let searchTimeout;
    $('#addFundCode').on('input', function() {
        const fundCode = $(this).val();
        clearTimeout(searchTimeout);
        
        if (fundCode.length >= 2) {
            searchTimeout = setTimeout(function() {
                fetchFundsForSearch(fundCode, function(funds) {
                    showFundSuggestions(funds);
                });
            }, 300);
        } else {
            $('#fundSuggestions').hide();
        }
    });

    // 点击页面其他地方隐藏建议列表
    $(document).on('click', function(e) {
        if (!$(e.target).closest('#addFundCode, #fundSuggestions').length) {
            $('#fundSuggestions').hide();
        }
    });

    // 基金代码输入框失去焦点时，自动获取基金名称
    $('#addFundCode').on('blur', function() {
        const fundCode = $(this).val();
        if (fundCode) {
            fetchFundsForSearch(fundCode, function(funds) {
                const fund = funds.find(f => f.fundCode === fundCode);
                if (fund) {
                    $('#addFundName').val(fund.fundName);
                } else {
                    $('#addFundName').val('');
                }
            });
        }
    });

    // 在页面加载时调用 fetchTransactions 函数以获取并渲染数据
    fetchTransactions();
});